import runpy
import sys
from rich.progress import Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
from rich.console import Console


console = Console()


def main() -> int:
    """Run try_plot.py while showing a rich spinner + elapsed time.

    Returns an exit code (0 on success)."""
    with Progress(
        SpinnerColumn(),
        TextColumn("[bold blue]运行 try_plot.py…"),
        TimeElapsedColumn(),
        transient=True,
    ) as progress:
        task_id = progress.add_task("run", total=None)
        try:
            runpy.run_path("try_plot.py", run_name="__main__")
            return 0
        finally:
            # ensure spinner stops promptly
            try:
                progress.stop_task(task_id)
            except Exception:
                pass


if __name__ == "__main__":
    from rich.console import Console
    from rich.panel import Panel
    from rich.text import Text
    import time as _time
    # custom start panel for try.py to visually distinguish it from other scripts
    start_time = _time.time()
    start_time_str = _time.strftime('%Y-%m-%d %H:%M:%S')
    Console().print(Panel(Text(f"⏱  运行 try_plot 开始 {start_time_str}", style="bold white on dark_blue"), expand=False))
    try:
        code = main()
        sys.exit(code if isinstance(code, int) else 0)
    except SystemExit as e:
        code = e.code if isinstance(e.code, int) else 0
        sys.exit(code)
    except Exception as e:
        Console().log(f'运行 try.py 出错：{e}')
        import traceback
        Console().log(traceback.format_exc())
        sys.exit(1)
    finally:
        end_time = _time.time()
        end_time_str = _time.strftime('%Y-%m-%d %H:%M:%S')
        duration = end_time - start_time
        body = Text()
        body.append(f"⌛️  运行 try_plot 结束 {end_time_str}\n", style="bold white")
        body.append(f"总耗时：{int(duration)} 秒（{duration/60:.2f} 分钟）", style="yellow")
        Console().print(Panel(body, style="on dark_blue", expand=False))
